﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CPPEI.ShareScreen.App.RemoteDesk
{
    public class UploadDeskThread
    {
        private Thread _thread;
        private bool _isRunning;
        private EventWaitHandle _waitHandle;

        private ScreenCapture2 _screenCapture;

        public UploadDeskThread(ScreenCapture2 screenCapture)
        {
            _screenCapture = screenCapture;
        }

        public void Start()
        {
            _waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
            _thread = new Thread(Running);
            _isRunning = true;
            _thread.Start();
        }

        public void Stop()
        {
            _isRunning = false;
            _waitHandle.WaitOne();
        }

        private void Running()
        {
            while (_isRunning)
            {
                System.Drawing.Bitmap bmp = _screenCapture.CaptureScreenToBitmap();

                byte[] data = BitmapToBytes(bmp);
                Event.NCL.NCLUploadDesktopEvent @event = new Event.NCL.NCLUploadDesktopEvent();
                @event.Data = data;
                CPPEI.Event.NCL.NCLEventBus.Publish(@event);
                
                Thread.Sleep(200);
            }
            _waitHandle.Set();
        }



        //Bitmap转byte[]  
        public static byte[] BitmapToBytes(Bitmap Bitmap)
        {
            MemoryStream ms = null;
            try
            {
                ms = new MemoryStream();

                //System.Drawing.Imaging.Encoder myEncoder3 = System.Drawing.Imaging.Encoder.ColorDepth;

                Bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                byte[] byteImage = new Byte[ms.Length];
                byteImage = ms.ToArray();
                //System.Diagnostics.Debug.WriteLine(string.Format("bitmap byte:{0}", byteImage.Length));
                return byteImage;

                //ms = new MemoryStream();
                //GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
                //Bitmap.Save(compressedzipStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                //compressedzipStream.Close();
                //byte[] byteImage = ms.ToArray();
                //System.Diagnostics.Debug.WriteLine(string.Format("bitmap byte:{0}", byteImage.Length));
                //return byteImage;
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
            }
        }
    }
}
